package com.ruitu.router_module.util;

import com.ruitu.arad.util.MD5Util;
import com.ruitu.router_module.Logg;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

// 请求拦截器
public class HealthInterceptor implements Interceptor {

    public static String KEY = "ruitu";// 用于加密的key

    @Override
    public Response intercept(Chain chain) throws IOException {
        String timestamp = String.valueOf(System.currentTimeMillis());// 当前请求时间戳
        Request orgRequest = chain.request();
        RequestBody body = orgRequest.body();

        //收集请求参数，方便调试
        StringBuilder paramsBuilder = new StringBuilder();
        if (body != null) {// 说明有请求实体(可以认为是post请求)
            RequestBody newBody = null;
            if (body instanceof FormBody) {// 普通的提交表单请求
                Logg.i("MultipartBody....");
//                newBody = addParamsToFormBody((FormBody) body, paramsBuilder);

                FormBody myBody = (FormBody) body;
                int bodySize = myBody.size();// 参数的个数
                if (bodySize <= 0) {
                    return chain.proceed(orgRequest);// 参数为0,直接返回(继续请求)不再做拦截处理
                }
                // 遍历所有参数,封装成json字符串
                paramsBuilder.append("{");
                for (int i = 0; i < bodySize; i++) {
                    paramsBuilder.append(myBody.name(i));
                    paramsBuilder.append(":");
                    paramsBuilder.append("\"");
                    paramsBuilder.append(myBody.value(i));
                    paramsBuilder.append("\"");
                    if (i == bodySize - 1) {// 最后一个参数不拼接","

                    } else {
                        paramsBuilder.append(",");
                    }
                }
                paramsBuilder.append("}");
                Logg.i("封装成json的post参数:    " + paramsBuilder.toString());
                // 生成一个随机的16位字符串
                String nonStr = UUID.randomUUID().toString().substring(0, 16);


            } else if (body instanceof MultipartBody) {// 可以认为是文件上传
                Logg.i("MultipartBody....");
                newBody = addParamsToMultipartBody((MultipartBody) body, paramsBuilder);
            } else {

            }

            if (null != newBody) {
//                Logg.i(paramsBuilder.toString());//打印参数
                Request newRequest = orgRequest.newBuilder()
                        .url(orgRequest.url())
                        .method(orgRequest.method(), newBody)
                        .build();
                return chain.proceed(newRequest);
            } else {
                return chain.proceed(orgRequest);
            }
        } else {// 说明没有请求实体(可以认为是get请求)
            HttpUrl oldUrl = orgRequest.url();
            int paramSize = 0;// get参数的个数
            try {
                paramSize = oldUrl.queryParameterNames().size();
                if (paramSize <= 0) {// 说明没有参数
                    return chain.proceed(orgRequest);// 参数为0,直接返回(继续请求)不再做拦截处理
                }
            } catch (Exception e) {
                e.printStackTrace();
                return chain.proceed(orgRequest);// 参数异常,直接返回(继续请求)不再做拦截处理
            }
            // 将参数名和值封装成一个map,按参数名进行排序
            Map<String, String> paramsMap = new TreeMap<>();
            // 遍历原始请求的参数,加入到map中进行排序
            for (int i = 0; i < paramSize; i++) {
                String name = oldUrl.queryParameterName(i);
                String value = oldUrl.queryParameterValue(i);
                paramsMap.put(name, value);
            }
            // 加入新字段的参数
            paramsMap.put("timestamp", timestamp);
            paramsMap.put("token", "token");
            paramsMap.put("key", KEY);
            // 得到排序后的参数列表(b=vb&a=va 变成 a=va&b=vb 的形式)
            for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                String key = entry.getKey();
                String val = entry.getValue();
                paramsBuilder.append(key);
                paramsBuilder.append("=");
                paramsBuilder.append(val);
                paramsBuilder.append("&");
            }
            // 处理排序后的参数列表字符串
            String tmpParams = paramsBuilder.toString();
            String newParams = tmpParams.substring(0, tmpParams.length() - 1);
//            Logg.i("newParams : " + newParams);
            // 加密排序后的参数字符串
            String sign = MD5Util.md5String(newParams).toUpperCase();// sign:排序参数加密后的字符串

            // oldUrl.newBuilder() 基于原始url构建新url可以保留原始的请求参数
            HttpUrl newUrl = oldUrl.newBuilder()
                    .addQueryParameter("sign", sign)
                    .addQueryParameter("timestamp", timestamp)
                    .addQueryParameter("token", "token")
                    .build();
            Request getReq = orgRequest.newBuilder()
                    .method(orgRequest.method(), orgRequest.body())
                    .url(newUrl)
                    .build();
            return chain.proceed(getReq);
        }
    }

    /**
     * 为MultipartBody类型请求体添加参数
     */
    private MultipartBody addParamsToMultipartBody(MultipartBody body, StringBuilder paramsBuilder) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        //添加token
//        builder.addFormDataPart(TOKEN_PARAM, getToken());
//        paramsBuilder.append("token=" + getToken());
//        paramsBuilder.append("&");
        //添加时间戳
//        builder.addFormDataPart(TIME_PARAM, getTimeStamp());
//        paramsBuilder.append("timestamp=" + getTimeStamp());

        //添加原请求体
        for (int i = 0; i < body.size(); i++) {
            builder.addPart(body.part(i));
        }
        return builder.build();
    }

    /**
     * 为FormBody类型请求体添加参数
     */
    private FormBody addParamsToFormBody(FormBody body, StringBuilder paramsBuilder) {
        FormBody.Builder builder = new FormBody.Builder();

        //添加token
//        builder.add(TOKEN_PARAM, getToken());
//        paramsBuilder.append("token=" + getToken());
//        paramsBuilder.append("&");
        //添加时间戳
//        builder.add(TIME_PARAM, getTimeStamp());
//        paramsBuilder.append("timestamp=" + getTimeStamp());

        //添加原请求体
        for (int i = 0; i < body.size(); i++) {
            builder.addEncoded(body.encodedName(i), body.encodedValue(i));
            paramsBuilder.append("&");
            paramsBuilder.append(body.name(i));
            paramsBuilder.append("=");
            paramsBuilder.append(body.value(i));
        }
        return builder.build();
    }
}
